package org.ihelpuoo.json;

import java.io.InputStream;

import org.ihelpuoo.orm.IIIException;
import org.ihelpuoo.orm.filter.FieldFilter;
import org.ihelpuoo.util.PagerList;

import com.sdicons.json.mapper.JSONMapper;
import com.sdicons.json.mapper.MapperException;
import com.sdicons.json.model.JSONArray;
import com.sdicons.json.model.JSONBoolean;
import com.sdicons.json.model.JSONDecimal;
import com.sdicons.json.model.JSONInteger;
import com.sdicons.json.model.JSONNull;
import com.sdicons.json.model.JSONObject;
import com.sdicons.json.model.JSONString;
import com.sdicons.json.model.JSONValue;
import com.sdicons.json.parser.JSONParser;

public class JSON
{

	public static String toJSONString(Object obj, boolean fmt)
	{
		return toJSONString(obj,fmt,null,null);
	}

	public static String toJSONString(Object obj, boolean fmt, FieldFilter actived,
			FieldFilter locked)
	{
		if (null == obj)
			return null;
		try
		{
			JSONValue v = JSONMapper.toJSON(obj);
			return v.render(fmt,"",actived,locked);
		}
		catch (MapperException e)
		{
			throw new RuntimeException(e);
		}
	}

	public static String toJSONString(PagerList obj, boolean fmt) throws IIIException
	{
		return toJSONString(obj,fmt,null,null);
	}

	public static String toJSONString(PagerList obj, boolean fmt, FieldFilter actived,
			FieldFilter locked)
	{
		if (null == obj)
			return null;
		try
		{
			JSONValue pager = JSONMapper.toJSON(obj.getPager());
			JSONValue list = JSONMapper.toJSON(obj.getList());
			StringBuffer sb = new StringBuffer();
			if (fmt)
			{
				sb.append("{\n    pager:").append(pager.render(false)).append(',');
				sb.append("\n    list:").append(list.render(fmt,"",actived,locked));
				sb.append('\n').append('}');
			}
			else
			{
				sb.append("{pager:").append(pager.render(false)).append(',');
				sb.append("list:").append(list.render(fmt,"",actived,locked)).append('}');
			}
			return sb.toString();
		}
		catch (MapperException e)
		{
			throw new RuntimeException(e);
		}
	}

	public static Object parseAs(InputStream ins, Object obj) throws IIIException
	{
		JSONParser parser = new JSONParser(ins);
		JSONValue v;
		try
		{
			v = parser.nextValue();
			if (v instanceof JSONObject)
			{

			}
			if (v instanceof JSONArray)
			{

			}
			else if (v instanceof JSONNull)
			{
				return null;
			}
			else if (v instanceof JSONString)
			{
				return ((JSONString)v).getValue();
			}
			else if (v instanceof JSONBoolean)
			{
				return new Boolean(((JSONBoolean)v).getValue());
			}
			else if (v instanceof JSONInteger)
			{
				return ((JSONInteger)v).getValue();
			}
			else if (v instanceof JSONDecimal)
			{
				return ((JSONDecimal)v).getValue();
			}
		}
		catch (Exception e)
		{
			throw new IIIException(e);
		}
		throw new IIIException("! Error " + v.getClass() + " is a surprise!");
	}
}
